import { HttpCode, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Message } from './entities/message.entity';
import { Conversation } from './entities/conversation.entity';
import { UserAccount } from 'src/user_account/entities/user_account.entity';
import { Repository } from 'typeorm';
@Injectable()
export class MessageService {
  constructor(@InjectRepository(Message) private readonly message: Repository<Message>,
    @InjectRepository(Conversation) private readonly conversation: Repository<Conversation>,
    @InjectRepository(UserAccount) private readonly userAccount: Repository<UserAccount>) { }


  async findMyConversation(userId: number) {
    try {
      const conversationList = await this.conversation.createQueryBuilder('conversation')
        .where('conversation.user1=:userId OR conversation.user2=:userId', { userId })
        .getManyAndCount()
      return {
        code: HttpStatus.OK,
        data: conversationList
      }
    } catch (error) {
      return {
        code: HttpStatus.BAD_GATEWAY,
        msg: '网络错误'
      }
    }


  }


  async createSession(createSessionDto: { senderId: number, receiverId: number }) {
    const { senderId, receiverId } = createSessionDto
    const [maxId, minId] = [Math.max(senderId, receiverId), Math.min(senderId, receiverId)]
    //首先查找是否存在两人之间的聊天
    const hasConversation = await this.conversation.createQueryBuilder('conversation')
      .leftJoinAndSelect('conversation.messages', 'messages')
      .leftJoinAndSelect('messages.sender', 'sender')
      .leftJoinAndSelect('messages.receiver', 'receiver')
      .where('conversation.user1=:minId and conversation.user2=:maxId', { minId, maxId })
      .groupBy('messages.id')
      .orderBy('messages.createdTime', "ASC")
      .getOne()
    if (!hasConversation) {
      const conversation = this.conversation.create({
        user1: minId, user2: maxId
      })
      const res = await this.conversation.save(conversation)
      const data = await this.conversation.findOne({ where: { id: res.id }, relations: ['messages'] })
      return {
        code: HttpStatus.OK,
        msg: '创建成功',
        data
      }
    } else {
      const unReads = await this.message.createQueryBuilder('message')
        .leftJoinAndSelect('message.conversation', 'conversation')
        .where('conversation.id=:id', { id: hasConversation.id })
        .andWhere('message.read =:read', { read: false })
        .getMany()
      for (const message of unReads) {
        message.read = true
        await this.message.save(message)
      }
      return {
        code: HttpStatus.FOUND,
        msg: '之前存在',
        data: hasConversation
      }
    }
  }


  async handleMessage(sendMessageDto: { senderId: number, receiverId: number, conversationId: number, read?: boolean, content: string }) {
    const { senderId, receiverId, conversationId, read, content } = sendMessageDto
    const sender = await this.userAccount.findOneById(senderId)
    const receiver = await this.userAccount.findOneById(receiverId)
    const conversation = await this.conversation.findOne({ where: { id: conversationId }, relations: ['messages'] })
    const message = this.message.create({
      sender,
      receiver,
      content,
      conversation,
      read
    })
    return await this.message.save(message)
  }


  async unReadCount(userId: number) {
    const unReadCount = await this.message.createQueryBuilder('message')
      .leftJoinAndSelect('message.receiver', 'receiver')
      .where('receiver.id=:userId', { userId })
      .andWhere('message.read=false')
      .getCount()
    return unReadCount;
  }

}
